<script setup>
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { reqUserLogin, reqUserInfo } from '@/api/users'
import { useUserStore } from '@/stores/modules/user'
const userStore = useUserStore()
// 路由实例
const router = useRouter()

// 表单引用
const loginFormRef = ref(null)

// 加载状态
const loading = ref(false)

// 登录表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3到20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 4, max: 20, message: '密码长度应在6到20个字符之间', trigger: 'blur' }
  ]
}

// 登录处理函数
const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        const result = await reqUserLogin(loginForm)
        if (result.msg === 'ok') {
          ElMessage.success('登录成功')
          // 存储token等信息到localStorage或pinia
          // localStorage.setItem('token', result.data.token)
          userStore.setToken(result.data.token)
          userStore.setUserLoginState(true)
          // 调用获取用户信息的接口
          const userInfo = await reqUserInfo()
          if (userInfo.msg !== 'ok') return ElMessage.error(userInfo.message || '获取用户信息失败')
          // 存储用户信息到pinia
          userStore.setUserInfo(userInfo.data)

          // 跳转到首页
          router.push('/')
        } else {
          ElMessage.error(result.message || '登录失败')
        }
      } catch (error) {
        console.error('登录出错:', error)
        ElMessage.error('登录失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<template>
  <el-row class="login-container">
    <el-col :lg="16" :md="12" class="left">
      <div class="text1">欢迎光临</div>
      <div class="text2">2025最新Vue3+Vite+ElemettPuls实战商城后台管理项目</div>
    </el-col>
    <el-col :lg="8" :md="12" class="right">
      <div>
        <div class="login-form">
          <h1>系统登录</h1>
          <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef">
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" placeholder="用户名" prefix-icon="User" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="loginForm.password" placeholder="密码" prefix-icon="Lock" type="password" show-password />
            </el-form-item>
            <el-form-item>
              <el-button color="#9197f4" type="primary" :loading="loading" @click="handleLogin" class="login-button"
                >登录</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-col>
  </el-row>
</template>

<style scoped lang="scss">
.login-container {
  min-height: 100vh;
  background-color: #6366f1;

  .left {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .text1 {
      font-size: 50px;
      /* 加粗 */
      font-weight: bold;
      color: #fff;
      margin-top: 80px;
    }

    .text2 {
      font-size: 20px;
      color: #fff;
      margin: 40px 0;
    }
  }

  .right {
    background-color: #fdfdfd;
    display: flex;
    flex-direction: column;
    justify-content: center;

    .login-form {
      padding: 40px;

      h1 {
        text-align: center;
        margin-bottom: 30px;
        font-size: 28px;
        font-weight: bold;
      }

      .login-button {
        width: 100%;
        border-radius: 20px;
      }
    }
  }
}
</style>
